#-*- coding: utf-8 -*-
from eve_static.models import *
from apiManager.models import *
import re
import locale
import math
#locale.setlocale(locale.LC_ALL, 'fr-ch')
#locale.format("%d", 1255000, grouping=True)

def select_dict_by_name(list_of_dict, name):
    y = {}
    for i in list_of_dict:
        if i['name'] == name:
            y = i
    return y

def list_production(list_mat, list_minimum, options, list_prod):
    options['lvl_sub_mat'] -= 1
    qle = options['qle']
    for i in list_mat:
        if (options['lvl_sub_mat'] >= 0 or list_minimum.count(i['typeid']) > 0) and i['materials'] != None:
            options['qle'] = i['qle']
            list_production(i['materials'], list_minimum, dict(**options), list_prod)
            # filtre schematic PSES
            if int(i['qle']) != 2 or int(qle) != 2 or options['pi'] != 'one go':
                dict_mat = select_dict_by_name(list_prod, i['name'])
                if dict_mat != {}:
                    dict_mat['qte'] += i['qte']
                else:
                    list_prod += [{'name':i['name'], 'qte':i['qte'], 'stage':options['lvl_sub_mat'], 'qle':i['qle'], 'runs':i['runs']}]
    return list_prod

def list_shopping(list_mat, list_minimum, options, list_shop):
    options['lvl_sub_mat'] -= 1
    for i in list_mat:
        if (options['lvl_sub_mat'] >= 0 or list_minimum.count(i['typeid']) > 0) and i['materials'] != None:
            list_shopping(i['materials'], list_minimum, dict(**options), list_shop)
        else:
            dict_mat = select_dict_by_name(list_shop, i['name'])
            assets = Asset.objects.filter(typeID = i['typeid'])
            qte_stock = 0
            for asset in assets:
                qte_stock += asset.quantity

            if dict_mat != {}:
                dict_mat['qte'] += i['qte']
                dict_mat['qte_stock'] = qte_stock
                dict_mat['qte_diff'] -= i['qte']
            else:
                qte_diff = qte_stock - i['qte']
                list_shop += [{'name':i['name'], 'qte':i['qte'], 'qle':i['qle'], 'qte_stock':qte_stock, 'qte_diff':qte_diff}]
    return list_shop


def update_list_mat_minimum(list_mat, list_minimum):
    for i in list_mat:
        if list_minimum.count(i['typeid']) == 0:
            i['minimum'] = 1
        else:
            i['minimum'] = 0
        if i['materials'] != None:
            update_list_mat_minimum(i['materials'], list_minimum)


def list_general(list_mat, list_minimum):
        for i in list_mat:
            if i['new'] == 1:
                i['typeid'] = Invtypes.objects.get(typename = i['name']).typeid
                i['minimum'] = 0
                if list_minimum.count(i['typeid']) == 0:
                    list_minimum.append(int(i['typeid']))
                    list_minimum.append(int(i['typeid']))
                i['list_minimum'] = list_minimum
                i['qle'] = 20
                i['lvl_sub_mat'] = 100
                i['bp_runs'] = 10
                psize = Invtypes.objects.get(typename = i['name']).portionsize
                i['runs'] = math.ceil(1.0*i['qte']/psize)
                i['qte'] = math.ceil(i['runs']*psize)
                i['materials'] = list_materials(i['typeid'], i)
                i['new'] = 0
            else:
                if list_minimum.count(i['typeid']) == 2:
                    i['minimum'] = 0
                else:
                    i['minimum'] = 1
                update_list_mat_minimum(i['materials'], list_minimum)
        return list_mat

def list_materials(typeid, options):
    list_mat = []
#    Invtypes.objects.select_related('blueprint', 'schematic').prefetch_related('get_materials', 'blueprint__get_materials', 'schematic__get_materials')
    item = Invtypes.objects.get(typeid=typeid)
    group = 0
    try:
        group = item.blueprint.techlevel
    except:
        pass
    try:
        item.schematic
        group = 0.5
    except:
        pass
        
    if group == 1:
        req = item.get_materials.all()
        
        for i in req:
            list_mat += sub_list_mat(i.requiredtypeid, i.quantity, 1, dict(**options))

    elif group == 2 or group == 3:
        req = item.blueprint.get_materials.filter(activityid=1).exclude(damageperjob=0)
        
        for i in req:
            list_mat += sub_list_mat(i.requiredtypeid, i.quantity*i.damageperjob, 10, dict(**options))

        sub_req = item.get_materials.all()
        
        for i in sub_req:
            try:
                item.blueprint.get_materials.get(recycle=1)
                list_mat += sub_list_mat(i.requiredtypeid, i.quantity-item.item_t1().get_materials.get(requiredtypeid=i.requiredtypeid.typeid).quantity, 2, dict(**options))
            except:
                list_mat += sub_list_mat(i.requiredtypeid, i.quantity, 2, dict(**options))
                            
        try:
            req = item.item_t1().blueprint.get_materials.filter(activityid=8).exclude(damageperjob=0)
            
            for i in req:
                list_mat += sub_list_mat(i.requiredtypeid, 1.0*i.quantity*i.damageperjob/options['bp_runs'], 4, dict(**options))

        except:
            pass
        
    elif group == 0.5:
        req = item.schematic.get_materials.filter(isinput=1)
        
        for i in req:
            list_mat += sub_list_mat(i.requiredtypeid, i.quantity, 0, dict(**options))
    
    else:
        list_mat = None
    return list_mat

def sub_list_mat(item, quantity, qle, options):
    if options['lvl_sub_mat'] == 0:
        return []
    if  re.compile('Data Interface').search(item.typename):
        return []
    if qle == 4 and not options['inv']:
        return []
    if quantity <= 0:
        return []
    
    temp = {}
    modt1 = 1.0
    modt2 = 1.5
    modinv = 2.0
    mod = 1.0
    if qle == 1:
        mod = modt1
    elif qle == 2:
        mod = modt2
    elif qle == 4:
        mod = modinv

    if item.groupid == 18:
        qle = 1.05
    elif item.groupid == 332:
        qle = 8.01
    elif item.groupid == 333:
        qle = 9.01
    elif item.groupid == 334:
        qle = 3.04
    elif item.groupid == 429:
        qle = 3.02
        mod = 1
    elif item.groupid == 423:
        qle = 4.01
    elif item.groupid == 964:
        qle = 6.06
    elif item.groupid == 966:
        qle = 6.02
    elif item.groupid == 974:
        qle = 6.03
    elif item.groupid == 1032:
        qle = 2.01
    elif item.groupid == 1033:
        qle = 2.01
    elif item.groupid == 1034:
        qle = 2.04
    elif item.groupid == 1035:
        qle = 2.04
    elif item.groupid == 1040:
        qle = 2.06
    elif item.groupid == 1042:
        qle = 2.02

 

    temp['name'] = item.typename
    temp['qte'] = math.ceil(mod*quantity)*options['runs']
    if qle == 8.01:
        temp['qte'] = mod*quantity*options['runs']
    try:
        temp['runs'] = math.ceil(1.0*temp['qte']/item.schematic.get_materials.get(isinput=0).quantity)
    except:
        temp['runs'] = math.ceil(1.0*temp['qte']/item.portionsize)
    temp['qle'] = qle
    temp['typeid'] = item.typeid
    
    if options['list_minimum'].count(item.typeid) == 0:
        temp['minimum'] = 1
    else:
        temp['minimum'] = 0
    options['qte'] = temp['qte']
    options['runs'] = temp['runs']
    options['lvl_sub_mat'] -= 1

    temp['materials'] = list_materials(item.typeid, dict(**options))
    if temp['materials'] != None:
        temp['materials'] = sorted(temp['materials'], key=lambda x: x['qte'], reverse=True)
        temp['materials'] = sorted(temp['materials'], key=lambda x: x['qle'], reverse=True)

    return [temp]







